const container = require('./ai_container.js');
const image = require('./ai_image.js');
const text = require('./ai_text.js');
const { genTextArb } = require('./utils.js');

function analyse(json) {
    console.log("analyse start");

    let infoList = json.info;
    let rectList = genHierarchy(infoList);
    let textList = rectList.filter((item) => {
        return item.type == "Text";
    })
    textList.forEach((item) => {
        console.log(genTextArb(item.info).arb);
    });
    rectList.forEach((item) => {
        genCode(item);
    });

    // let rootList = rectList.filter((item) => {
    //     // console.log("search root", item.id, !item.parent);
    //     return item.parent == null;
    // });

    // console.log("analyse end", rootList);
    // for (let i = 0; i < rootList.length; i++) {
    //     let root = rootList[i];
    //     printLevel(root, 0);
    // }
}

function genCode(rect) {
    let info = rect.info;
    let code  = "";
    if (rect.type == "Container") {
        code = container.convertToContainer(info);
    } else if (rect.type == "Image") {
        code = image.convertToImage(info);
    } else if (rect.type == "Text") {
        code = text.convertToText(info);
    }
    console.log(code);
}

function reduceNest(rect, level) {
    console.log(`${'-'.repeat(level)}| ${rect.type} === ${rect.id}`);
    if (rect.children && rect.children.length > 0) {
        if (rect.children.length == 1) {
            let child = rect.children[0];
            if (child.children && child.children.length == 1) {
                let grand = child.children[0];
                
            }
        }
        for (let i = 0; i < rect.children.length; i++) {
            reduceNest(rect.children[i], level + 1);
        }
    }
}

function printLevel(rect, level) {
    console.log(`${'-'.repeat(level)}| ${rect.type} === ${rect.id}`);
    if (rect.children && rect.children.length > 0) {
        if (rect.children.length > 1) {
            console.log("");
        }
        for (let i = 0; i < rect.children.length; i++) {
            printLevel(rect.children[i], level + 1);
        }
    }
}

function genRect(infoList) {
    let rectList = [];

    /// 从底层开始遍历
    for (let i = 0; i < infoList.length; i++) {
        let info = infoList[i];
        let rect = preRect(info);
        rect.level = i;

        if (rect.type != "Text" && rect.type != "Image" && info.hasExportDDSImage == false) {
            continue;
        }
        if (info.type == "symbol") {
            continue;
        }
        rectList.push(rect);
    }

    return rectList;
}

function layoutRect(rectList) {
    for (let i = 0; i < rectList.length; i++) {
        let rect = rectList[i];

        // 寻找重叠
        for (let j = 0; j < rectList.length; j++) {
            if (i == j) {
                continue;
            }
            let other = rectList[j];
            if (isIntersect(rect, other) && !isParent(rect, other)) {
                
            }
        }
    }
}

function genHierarchy(infoList) {
    console.log("genHierarchy start");

    let rectList = [];

    /// 从底层开始遍历
    for (let i = 0; i < infoList.length; i++) {
        let info = infoList[i];
        let rect = preRect(info);
        rect.level = i;

        if (rect.type != "Text" && rect.type != "Image" && info.hasExportDDSImage == false) {
            // console.log("skip", rect.type, rect.id);
            continue;
        }
        if (info.type == "symbol") {
            continue;
        }
        rectList.push(rect);
    }

    /// 从顶层开始遍历
    for (let i = rectList.length - 1; i >= 0; i--) {
        let rect = rectList[i];
        let parent = findParent(rectList, rect);
        if (parent != null) {
            rect.parent = parent;
            if (!parent.children) {
                parent.children = [];
            }
            parent.children.push(rect);
        }
    }

    for (let i = 0; i < rectList.length; i++) {
        let rect = rectList[i];
        figure(rect);
    }
    console.log("genHierarchy end");

    return rectList
}

function preRect(info) {
    var rect = {};
    rect.id = info.id;
    rect.x = info.left;
    rect.y = info.top;
    rect.width = info.width;
    rect.height = info.height;
    rect.info = info;

    if (info.fills && info.fills.length > 0) {
        rect.type = "Container";
    } else if (info.font) {
        rect.type = "Text";
    } else if (info.image) {
        rect.type = "Image";
    }

    return rect;
}

function findParent(rectList, rect) {
    if (rectList.length == 0) {
        return null;
    }
    let parent = null;
    let choisise = [];
    /// 倒序遍历
    for (let i = rectList.length - 1; i >= 0; i--) {
        let r = rectList[i];
        if (isParent(r, rect)) {
            // parent = r;
            choisise.push(r);
        }
    }

    if (choisise.length > 0) {
        for (let i = 0; i < choisise.length; i++) {
            let r = choisise[i];
            if (parent == null) {
                parent = r;
            } else if (parent.width > r.width || parent.height > r.height) {
                parent = r;
            }
        }
    }
    return parent;
}

function isParent(parent, child) {
    if (child.level == 0 || parent.id == child.id) {
        return false;
    }
    if (parent.type == "Image" || parent.type == "Text") {
        return false;
    }
    if (child.children && child.children.length > 0) {
        for (let i = 0; i < child.children.length; i++) {
            if (child.children[i].id == parent.id) {
                return false;
            }
        }
    }
    let res = parent.x <= child.x
        && parent.y <= child.y
        && parent.x + parent.width >= child.x + child.width
        && parent.y + parent.height >= child.y + child.height;
    return res;
}

function figure(rect) {
    let info = rect.info;
    if (info.fills && info.fills.length > 0) {
        rect.type = "Container";
        return;
    }

    if (info.font) {
        rect.type = "Text";
        return;
    }

    if (info.image) {
        rect.type = "Image";
        return;
    }

    if (rect.children && rect.children.length > 0) {
        // if (rect.children.length == 1) {
        //     rect.type = "Empty";
        // }

        let width = rect.children[0].width;
        let height = rect.children[0].height;
        let first = rect.children[0];
        for (let i = 1; i < rect.children.length; i++) {
            let child = rect.children[i];

            if (width == child.width && height != child.height) {
                rect.type = "Column";
                break;
            }

            if (height == child.height && width != child.width) {
                rect.type = "Row";
                break;
            }

            if (isIntersect(first, child)) {
                rect.type = "Stack";
                break;
            }
        }

        // if (!rect.type) {
        //     rect.type = "Group";
        // }
    }

    if (!rect.type) {
        rect.type = "SizedBox";
    }
}

function isIntersect(rect1, rect2) {
    // 矩形1的左上角和右下角坐标
    var x1 = rect1.x;
    var y1 = rect1.y;
    var x2 = rect1.x + rect1.width;
    var y2 = rect1.y + rect1.height;

    // 矩形2的左上角和右下角坐标
    var x3 = rect2.x;
    var y3 = rect2.y;
    var x4 = rect2.x + rect2.width;
    var y4 = rect2.y + rect2.height;

    // 如果一个矩形的右边缘在另一个矩形的左边缘右侧，或者一个矩形的下边缘在另一个矩形的上边缘下方，
    // 则这两个矩形不相交。
    if (x2 < x3 || x4 < x1 || y2 < y3 || y4 < y1) {
        return false;
    } else {
        return true; // 否则，矩形相交
    }
}

const fs = require('fs');
function readJSONFile() {
    // try {
      const fileData = fs.readFileSync("./sketch.json", 'utf-8');
      const jsonData = JSON.parse(fileData);
      analyse(jsonData);
    // } catch (error) {
    //   console.error(`Error reading JSON file: ${error.message}`);
    // }
}
readJSONFile();
  